package com.leyou.order.interceptors;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.holders.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1.获取cookie中的token
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
        // 2.解析token
        try {
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);

            // 3.获取用户
            UserInfo user = payload.getUserInfo();

            // 4.保存用户，向后传递
            UserHolder.setUser(user);

            return true;
        } catch (UnsupportedEncodingException e) {

            log.error("解析用户信息失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
